<template>
  <ContentDetailWrap @back="handleClose">
    <template #header>
      <BaseButton @click="go(-1)">{{ t('common.back') }}</BaseButton>
    </template>
    <el-form :model="form" label-width="88px">
      <div class="w-full grid grid-cols-3 gap-x-20px">
        <el-form-item label="仓库">
          <el-select v-model="parentRow.wid" placeholder=" " clearable disabled>
            <el-option
              v-for="item in warehouseList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称">
          <el-input v-model="parentRow.product_name" disabled placeholder=" " />
        </el-form-item>
        <el-form-item label="商品编码">
          <el-input v-model="parentRow.product_code" disabled placeholder=" " />
        </el-form-item>
        <el-form-item label="品牌">
          <el-select v-model="parentRow.brand" placeholder=" " clearable disabled>
            <el-option
              v-for="item in brandList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="算力">
          <el-input v-model="parentRow.hashrate" disabled placeholder=" " />
        </el-form-item>
        <el-form-item label="保修期">
          <el-input v-model="parentRow.expiration_date" disabled placeholder=" " />
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="parentRow.is_futures" placeholder=" " clearable disabled>
            <el-option
              v-for="item in warehouseTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="到货日期">
          <el-input v-model="parentRow.arrival_date" disabled placeholder=" " />
        </el-form-item>
        <el-form-item label="可转数量">
          <el-input v-model="parentRow.pay_quantity" disabled placeholder=" " />
        </el-form-item>
        <el-form-item label="可发货数量">
          <el-input v-model="parentRow.waiting_shipment_quantity" disabled placeholder=" " />
        </el-form-item>
      </div>
    </el-form>
    <!--      table-->
    <el-table
      :data="tableData"
      border
      class="mt-20px"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center', background: '#f8f8f9', color: '#333333' }"
    >
      <el-table-column prop="warehouse_name" label="仓库" :show-overflow-tooltip="true" />
      <el-table-column prop="create_time" label="入库时间" :show-overflow-tooltip="true" />
      <el-table-column prop="inbound_batch" label="批次号" :show-overflow-tooltip="true" />
      <el-table-column prop="available_qty" label="可用库存数量" :show-overflow-tooltip="true" />
      <el-table-column label="是否可售" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{ row.is_sale === 1 ? '可售' : '不可售' }}
        </template>
      </el-table-column>
      <el-table-column prop="order_no" label="转换数量" :show-overflow-tooltip="true">
        <template #default="{ row }">
          <el-form
            :model="row"
            :ref="setConvertibleRuleRef"
            :hide-required-asterisk="true"
            class=""
          >
            <el-form-item
              label=""
              prop="convertible_qty"
              :rules="convertibleRuleFn(row)"
              class="table-form"
            >
              <el-input
                v-model="row.convertible_qty"
                placeholder="请输入转换数量"
                @input="(e: string) => (row.convertible_qty = e.replace(/^(0+)|\D+/g, ''))"
              />
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
    </el-table>

    <!-- 发货订单列表 -->
    <el-table
      :data="tableOrderList"
      class="mt-20px"
      border
      :cell-style="{ textAlign: 'center' }"
      row-key="id"
      :header-cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
      ref="orderTableRef"
    >
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column
        :label="t('wholesalOrder.orderNo')"
        prop="order_no"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.username')"
        prop="user"
        min-width="250"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.deliveryAddress')"
        prop="shipping_address"
        min-width="350"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.receiptMethod')"
        min-width="200"
        :show-overflow-tooltip="true"
      >
        <template #default="{ row }">
          {{ useEnumeratePicker(deliveryMethodList, row.delivery_method) }}
        </template>
      </el-table-column>
      <el-table-column
        :label="t('order.quantity')"
        prop="quantity"
        min-width="200"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        :label="t('wholesalOrder.logisticsCosts')"
        prop="logistics_fee"
        min-width="200"
        :show-overflow-tooltip="true"
      />
    </el-table>

    <div class="flex justify-end w-full pt-20px">
      <el-button class="m-r-4" @click="handleClose">
        {{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit">
        {{ t('order.confirm') }}
      </el-button>
    </div>
  </ContentDetailWrap>
</template>
<script setup lang="ts">
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox, ElInput } from 'element-plus'
import {
  inventoryTypeConversionApi,
  getInventoryEnumApi,
  getEnumApi,
  getInventoryConversionTypeApi
} from '@/api/wholesalOrder'
import { oneDimensionalArraySummation } from '@/utils'
import { useTagsView } from '@/hooks/web/useTagsView'
const { closeCurrent } = useTagsView()
const { go, push } = useRouter()
import { useEnumeratePicker } from '@/utils'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

const { query } = useRoute()
const form = ref<Record<string, any>>({})

const parentRow = ref<Record<string, any>>({})

const tableData = ref<Array<Record<string, any>>>([])

const warehouseList = ref<Array<Record<string, any>>>([])
const warehouseTypeList = ref<Array<Record<string, any>>>([])
const brandList = ref<Array<Record<string, any>>>([])

const convertibleRuleRef = ref<FormInstance[]>([])

const setConvertibleRuleRef = (e) => {
  e && convertibleRuleRef.value.push(e)
}

const convertibleRuleFn = (row: Record<string, any>) => {
  return [
    {
      required: true,
      trigger: ['blur'],
      validator: (rule: Record<string, any>, value: string, callback: Function) => {
        if (!value) {
          callback()
        } else {
          if (parseFloat(value) > parseFloat(row.available_qty)) {
            callback(new Error(t('输入的转换数量不能大于可用库存数量')))
          } else {
            callback()
          }
        }
      }
    }
  ]
}

const submit = async () => {
  if (!tableData.value.length) return ElMessage.error('未匹配到库存数据，暂无法提交')
  const convertibleRuleResultList = await Promise.all(
    convertibleRuleRef.value.map(async (item) => await item.validate((valid) => valid))
  )
  if (!convertibleRuleResultList.every((item) => item))
    return ElMessage.error('输入的转换数量不能大于可用库存数量')
  // 筛选出 convertible_qty 存在的子元素
  const validItems = tableData.value.filter((item) => item.convertible_qty)
  if (validItems.length > 0) {
    // 获取第一个有效子元素的 wid
    const firstWid = validItems[0].wid
    // 检查所有有效子元素的 wid 是否和第一个一样
    if (!validItems.every((item) => item.wid === firstWid)) {
      return ElMessage.error('不允许跨仓转换')
    }
  } else {
    return ElMessage.error('请输入转换数量')
  }
  let sum = multipleSelection.value.reduce((pre, cur) => pre + cur.quantity, 0)
  if (
    parseFloat(oneDimensionalArraySummation(tableData.value, 'convertible_qty', 0)) - sum >
    parseFloat(parentRow.value.waiting_shipment_quantity)
  )
    return ElMessage.error('列表内填写的转换数量总和不能大于可发货数量和选中订单的数量之和')
  if (
    parseFloat(oneDimensionalArraySummation(tableData.value, 'convertible_qty', 0)) <
    parseFloat(sum)
  )
    return ElMessage.error('列表内填写的转换数量总和不能小于选中订单的数量之和')

  ElMessageBox.confirm('库存类型转换确认之后无法修改，请谨慎操作', t('purchase.logistics.tips'), {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      let params = {
        id: parentRow.value.order_item_id,
        productid: parentRow.value.product_id,
        arrival_date: parentRow.value.arrival_date,
        is_futures: 0,
        wid: parentRow.value.wid,
        list: tableData.value.flatMap((item) =>
          item.convertible_qty ? [{ id: item.id, quantity: item.convertible_qty }] : []
        ),
        associated_delivery_order_ids: multipleSelection.value.map((e) => e.id),
        associated_delivery_order_items_ids: multipleSelection.value.map((e) => e.order_item_id)
      }
      console.log('params', params)
      const resp = await inventoryTypeConversionApi(params)
      if (resp.code === 0) {
        ElMessage.success('操作成功')
        handleClose()
        emit('refresh')
      }
    })
    .catch(() => {})
}

const handleClose = () => {
  // 返回列表页关闭当前页
  closeCurrent()
  if (query.order_id && query.wholesal_id) {
    push(`/order/order-management/orderInventoryTypeConversion?id=${query.order_id}`)
  } else if (query.order_id && !query.wholesal_id) {
    push(`/order/wholesal-order-management/wholesalInventoryTypeConversion?id=${query.order_id}`)
  }
}

const deliveryMethodList = ref<any>([])
const getOptions = async () => {
  const resp = await getInventoryEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  warehouseList.value = resp.data.wid
  warehouseTypeList.value = resp.data.is_futures
  const response = await getEnumApi({ field: 'all' })
  deliveryMethodList.value = response.data.delivery_method
}
const tableOrderList = ref<any>([])
const getInventoryDetail = async () => {
  let params = {
    order_item_id: query.order_item_id,
    wholesal_id: query.wholesal_id ? query.wholesal_id : '',
    order_id: query.order_id
  }
  const resp = await getInventoryConversionTypeApi(params)
  console.log('详情', resp)
  parentRow.value = resp.data.products
  tableOrderList.value = resp.data.order_list
  tableData.value = resp.data.inventory_list
  if (query.order_id) {
    console.log('tableOrderList.value', tableOrderList.value)
    await nextTick()
    let defaultRow = tableOrderList.value.find((e) => e.id == query.order_id)
    console.log('defaultRow', defaultRow)
    defaultRow && orderTableRef.value.toggleRowSelection(defaultRow, true)
  }
}

// 设置默认选中的行
const orderTableRef = ref()
onMounted(async () => {
  console.log('query', query)
  if (query.order_id && query.order_item_id) {
    await getOptions()
    getInventoryDetail()
  }
})
//批量勾选
const multipleSelection = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  console.log('val', val)
  multipleSelection.value = val
}
</script>
<style lang="less" scoped>
.table-form {
  margin-bottom: 0 !important;
}
</style>
